package com.typhoon.spring_jdbctemplate.dao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.BeanPropertyRowMapper;

import com.typhoon.spring_jdbctemplate.dao.support.CustomJdbcTemplate;
import com.typhoon.spring_jdbctemplate.dao.support.PageQuery;
import com.typhoon.spring_jdbctemplate.dao.support.PageResult;
import com.typhoon.spring_jdbctemplate.entity.User;
import com.typhoon.spring_jdbctemplate.util.DataSourceUtils;

/**
 * 用户操作dao
 * 
 * @author Typhoon
 * @date 2017-08-22 15:32 Tuesday
 * @since V1.3.1
 */
public class UserDao {

	/**
	 * 获取jdbcTemplate
	 */
	//private JdbcTemplate jdbcTemplate = DataSourceUtils.getJdbcTemplate();
	private CustomJdbcTemplate jdbcTemplate = DataSourceUtils.getCustomJdbcTemplate();
	/**
	 * 查询列表
	 * 
	 * @return
	 */
	public List<User> queryAll() {
		return jdbcTemplate.query(" select * from User ", BeanPropertyRowMapper.newInstance(User.class), new Object[] {});
	}

	public User selectById(Long id) {
		List<User> list = jdbcTemplate.query("  select * from User where id = ? limit 1  ", BeanPropertyRowMapper.newInstance(User.class),id);
		if(null == list || list.isEmpty()) {
			return null;
		}
		return list.get(0);
	}
	
	public User update(User user) {
		jdbcTemplate.update(" update User set name = ?  where id = ? ", user.getName(),user.getId());
		return user;
	}
	
	public PageResult<User> page(PageQuery pageQuery,Map<String,Object> params) {
		StringBuilder sql = new StringBuilder();
		List<Object> paramList = new ArrayList<>();
		sql.append(" select * from User where 1 = 1 ");
		Object id = params.get("id");
		if(null != id) {
			sql.append(" and ").append(" id =?  ");
			paramList.add(id);
		}
		Object name = params.get("name");
		if(null != name) {
			sql.append(" and  ").append("	name = ?	");
			paramList.add(name);
		}
		
		sql.append("  order by createTime desc  ");
		
		return this.jdbcTemplate.page(sql.toString(), BeanPropertyRowMapper.newInstance(User.class), pageQuery, paramList.toArray());
	}
}
